package com.saer.server.network;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.saer.client.dto.network.MsgDto;
import com.saer.server.service.impl.NetworkServiceImpl;

public class DaemonThread extends Thread {

	private Logger log = LoggerFactory.getLogger(DaemonThread.class);

	private ConcurrentHashMap<Integer, ExpiringQueue<MsgDto>> visitasEntrantes;

	public DaemonThread() {
		this.visitasEntrantes = NetworkServiceImpl.getVisitasEntrantes();
		this.setDaemon(true);
		this.start();
	}

	public void run() {
		while (true) {
			for (Integer clientId : visitasEntrantes.keySet()) {
				ExpiringQueue<MsgDto> clientQueue = visitasEntrantes.get(clientId);
				if (clientQueue.getRemainigLives() <= 0) {
					visitasEntrantes.remove(clientId);
					log.info("El cliente [" + clientId + "] fue eliminado por superar el limite de inactividad.");
				} else {
					clientQueue.decRemainigLives();
					log.info("Al cliente [" + clientId + "] le quedan <" + clientQueue.getRemainigLives() + "> vidas.");
				}
			}

			try {
				// corre cada 10 min
				Thread.sleep(600000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
